<template>
  <div class="farm-record-dialog">
    <el-dialog :visible.sync="dialogFormVisible"
               :append-to-body="true"
               :close-on-click-modal="false"
               class="custom-dialog"
               @close="close"
               @open="open">
      <div slot="title">
        <div style="color:#fff">{{title}}</div>
      </div>
      <el-form :model="farmRecordForm" :rules="farmRecordRules" ref="farmRecordForm">
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="农事类型" :label-width="formLabelWidth" prop="eventType">
              <el-select v-model="farmRecordForm.eventType" placeholder="请选择农事类型" :disabled="type=='detail'"
                         style="width:100%">
                <el-option v-for="item in farmEventOptions" :key="item.eventId" :label="item.eventName"
                           :value="item.eventId"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="处理时间" :label-width="formLabelWidth" prop="handleTime">
              <el-date-picker
                :disabled="type=='detail'"
                style="width:100%"
                v-model="farmRecordForm.handleTime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择接入时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-form-item label="农机投入" :label-width="formLabelWidth" prop="putInto" style="position:relative">
            <div style="float: right" v-if="type!='detail'">
              <el-button type="primary" @click="handleClickAddMachine">添加农机</el-button>
            </div>
          </el-form-item>
          <el-form-item prop="putMachineIntoDetail">
            <el-table
              :header-cell-style="tableHeaderColor"
              :row-class-name="tableRowClassName"
              :data="putMachineTableData"
              style="width: 100%">
              <el-table-column
                align="center"
                label="农机">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.machineryName" placeholder="请选择农机" filterable :disabled="type=='detail' || scope.row.selectStatus"
                             @change="handleChangeMachine($event, scope.$index)"
                             style="width:100%" size="mini">
                    <el-option v-for="item in machineTypeOptions" :key="item.id" :label="item.machineryName" :value="item.id"></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                show-tooltip-when-overflow
                label="分类">
                <template slot-scope="scope">
                  <span>{{scope.row.machineryTypeName}}</span>
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="型号">
                <template slot-scope="scope">
                  <span>{{scope.row.brand}}</span>
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="投入费用">
                <template slot-scope="scope">
                  <el-input v-model.trim="scope.row.inputCost" autocomplete="off" placeholder="请输入"
                            :disabled="type=='detail'" style="width:100%" @change="changeCostInputs(scope.row, scope.$index)">
                    <template slot="append">
                      <div style="padding:0px;margin:0px">元/亩</div>
                    </template>
                  </el-input>
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="投入时长">
                <template slot-scope="scope">
                  <el-input v-model.trim="scope.row.time" autocomplete="off" placeholder="请输入"
                            :disabled="type=='detail'" style="width:100%" @change="changeTimeInputs(scope.row, scope.$index)">
                    <template slot="append">
                      <div style="padding:0px;margin:0px">时/亩</div>
                    </template>
                  </el-input>
                </template>
              </el-table-column>

              <el-table-column v-if="type!='detail'" width="60" align="center" label="操作">
                <template slot-scope="scope">
                  <el-popconfirm
                    @confirm="handleClickDeleteMachine(scope.row,scope.$index)"
                    title="确定删除这条农资投入记录吗？"
                  >
                    <el-button type="text" style="color:red" slot="reference">删&nbsp;除
                    </el-button>
                  </el-popconfirm>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-row>
        <!--        <el-row :gutter="10">-->
        <!--          <el-col :span="12">-->
        <!--            <el-form-item label="农机投入" :label-width="formLabelWidth" prop="machineType">-->
        <!--              <el-select v-model="farmRecordForm.machineType" placeholder="请选择农机" :disabled="type=='detail'"-->
        <!--                         style="width:100%" @change="handleChangeMachine">-->
        <!--                <el-option v-for="item in machineTypeOptions" :key="item.machineId" :label="item.machineName"-->
        <!--                           :value="item.machineId"></el-option>-->
        <!--              </el-select>-->
        <!--            </el-form-item>-->
        <!--          </el-col>-->
        <!--          <el-col :span="12">-->
        <!--            <el-form-item label="选择型号" :label-width="formLabelWidth" prop="modelType">-->
        <!--              <el-select v-model="farmRecordForm.modelType" placeholder="请选择型号" :disabled="type=='detail'"-->
        <!--                         style="width:100%">-->
        <!--                <el-option v-for="item in modelOptions" :key="item.modelId" :label="item.modelName"-->
        <!--                           :value="item.modelId"></el-option>-->
        <!--              </el-select>-->
        <!--            </el-form-item>-->
        <!--          </el-col>-->
        <!--        </el-row>-->
<!--        <el-row :gutter="10">-->
<!--          <el-col :span="12">-->
<!--            <el-form-item label="投入费用" :label-width="formLabelWidth" prop="cost">-->
<!--              <el-input v-model.trim="farmRecordForm.cost" autocomplete="off" placeholder="请填写费用"-->
<!--                        :disabled="type=='detail'" style="width:100%">-->
<!--                <template slot="append">元/亩</template>-->
<!--              </el-input>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="12">-->
<!--            <el-form-item label="投入时长" :label-width="formLabelWidth" prop="time">-->
<!--              <el-input v-model.trim="farmRecordForm.time" autocomplete="off" placeholder="请填写时长"-->
<!--                        :disabled="type=='detail'" style="width:100%">-->
<!--                <template slot="append">小时/亩</template>-->
<!--              </el-input>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--        </el-row>-->
        <el-row>
          <el-col :span="24">
            <el-form-item label="农资投入" :label-width="formLabelWidth" prop="putInto" style="position:relative">
              <div style="float: right" v-if="type!='detail'">
                <el-button type="primary" @click="handleClickAddItem">添加农资</el-button>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item prop="putIntoDetail">
          <el-table
            :header-cell-style="tableHeaderColor"
            :row-class-name="tableRowClassName"
            :data="putTableData"
            style="width: 100%">
<!--            <el-table-column-->
<!--              align="center"-->
<!--              label="农资">-->
<!--              <template slot-scope="scope">-->
<!--                <el-cascader-->
<!--                  v-model="scope.row.material"-->
<!--                  style="width:100%"-->
<!--                  clearable-->
<!--                  :props="machineProps"-->
<!--                  :options="materialOptions"></el-cascader>-->
<!--              </template>-->
<!--            </el-table-column>-->
            <el-table-column
              align="center"
              label="农资">
              <template slot-scope="scope">
                <el-select v-model="scope.row.material" placeholder="请选择农资" filterable :disabled="type=='detail' || scope.row.selectStatus"
                           @change="handleChangeGoods($event, scope.$index)"
                           style="width:100%" size="mini">
                    <el-option v-for="item in materialOptions" :key="item.id" :label="item.goodsName" :value="item.id"></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              show-tooltip-when-overflow
              label="分类">
              <template slot-scope="scope">
                <span>{{scope.row.materialType}}</span>
<!--                <el-select v-model="scope.row.category" placeholder="请选择分类" :disabled="type=='detail'"-->
<!--                           style="width:100%" size="mini">-->
<!--                  <el-option v-for="item in categoryOptions" :key="item.categoryId" :label="item.categoryName"-->
<!--                             :value="item.categoryId"></el-option>-->
<!--                </el-select>-->
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="型号">
              <template slot-scope="scope">
                <span>{{scope.row.materialBrand}}</span>
<!--                <el-select v-model="scope.row.model" placeholder="请选择型号" :disabled="type=='detail'" style="width:100%"-->
<!--                           size="mini">-->
<!--                  <el-option v-for="item in modelOptions" :key="item.modelId" :label="item.modelName"-->
<!--                             :value="item.modelId"></el-option>-->
<!--                </el-select>-->
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              width="80"
              label="规格">
              <template slot-scope="scope">
                <span>{{scope.row.specs}}</span>{{scope.row.meteringUnit}}/{{scope.row.unit}}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="投入量">
              <template slot-scope="scope">
                <el-input v-model.trim="scope.row.inputs" autocomplete="off" placeholder="请输入"
                          :disabled="type=='detail'" style="width:100%" @change="changeGoodsInputs(scope.row, scope.$index)">
                  <template slot="append">
                    <div style="padding:0px;margin:0px">{{scope.row.unit}}</div>
                  </template>
                </el-input>
              </template>
            </el-table-column>
            <el-table-column
              v-if="type!='detail'"
              align="center"
              label="最大量">
              <template slot-scope="scope">
                {{scope.row.maxInputs}}{{scope.row.unit}}
              </template>
            </el-table-column>
            <el-table-column
              width="70"
              align="center">
              <template slot-scope="scope">
                <span>{{scope.row.unit}}/亩</span>
              </template>
            </el-table-column>
            <el-table-column v-if="type!='detail'" width="60" align="center" label="操作">
              <template slot-scope="scope">
                <el-popconfirm
                  @confirm="handleClickDelete(scope.row,scope.$index)"
                  title="确定删除这条农资投入记录吗？"
                >
                  <el-button type="text" style="color:red" slot="reference">删&nbsp;除
                  </el-button>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="备注" :label-width="formLabelWidth" prop="remarks">
          <el-input v-model.trim="farmRecordForm.remarks"
                    style="width:100%"
                    :disabled="type=='detail'"
                    type="textarea"
                    :rows="3"
                    placeholder="请输入备注信息"/>
        </el-form-item>
      </el-form>
      <div v-if="type!='detail'" slot="footer" style="margin-top:-34px">
        <el-button type="primary" @click="handleClickSubmit" :loading="addStatus">完&nbsp;&nbsp;成
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
    import { getUUID } from '@/utils'
    import {
        goodsKCList,
        machineryKCList,
        typelistMaterial
    } from "@/api/material";
    import {
        queryPlantType,
        batchAddFarmRecord
    } from "@/api/affairs"
    export default {
        data() {
            return {
                type: "",
                title: "农事记录",
                dialogFormVisible: false,
                targetIds:[],
                addStatus: false,
                formLabelWidth: '80px',
                farmRecordForm: {
                    handleTime: "",
                    eventType: "",
                    remarks: ""
                },
                machineProps: {
                    multiple: false,
                    checkStrictly: true,
                    value: "id",
                    label: "goodName",
                    children: "children"
                },
                farmRecordRules: {
                    eventType:[
                        {required: true, message: '请选择类型', trigger: 'change'}
                    ],
                    handleTime:[
                        {required: true, message: '处理开始时间不能为空', trigger: 'change'},
                    ]
                },
                farmEventOptions: [],
                machineTypeOptions: [],
                machineTypeDeleteOptions: [],
                modelOptions: [],
                materialOptions: [],
                materialDeleteOptions:[],
                categoryOptions: [],
                putTableData: [],
                putMachineTableData: []
            }
        },
        methods: {
            show(status, typeLabel, obj) {
                this.putTableData = []
                switch (typeLabel) {
                    case 'add':
                        const {ids} = obj
                        // 已选中的地块信息
                        this.targetIds = ids
                        this.type = 'add'
                        this.farmRecordForm = {
                            handleTime: "",
                            eventType: "",
                            remarks: ""
                        }
                        this.handleClickAddItem()
                        this.handleClickAddMachine()
                        break;
                    case 'detail':
                        const {farmType,proposal,dealTime,goodsList,machineList} = obj
                        this.type = 'detail'
                        this.farmRecordForm = {
                            handleTime: dealTime,
                            eventType: farmType,
                            remarks: proposal
                        }
                        this.putTableData = []
                        if(goodsList && goodsList.length>0){
                            this.putTableData = goodsList.map(item=>{
                                const obj = {
                                    id: getUUID(),
                                    goodsId: getUUID(),
                                    material:item.materialName,
                                    materialType:item.materialTypeName,
                                    materialBrand:item.brand,
                                    model:item.model,
                                    meteringUnit:item.meteringUnit,
                                    price:item.price ? (item.price*1)/100 : 0,
                                    unit:item.unit,
                                    specs:item.specs,
                                    inputs:item.qty
                                }
                                return obj
                            })
                        }
                        if(machineList && machineList.length>0){
                            this.putMachineTableData = machineList.map(item=>{
                                const obj = {
                                    id: getUUID(),
                                    machineryId: getUUID(),
                                    machineryName:item.materialName,
                                    machineryTypeName:item.materialTypeName,
                                    brand:item.brand,
                                    model:item.model,
                                    price:item.price ? (item.price*1)/100 : 0,
                                    time:item.qty,
                                    inputCost:item.price ? (item.price*1)/100 : 0
                                }
                                return obj
                            })
                        }
                        break;
                }
                this.dialogFormVisible = status
            },

            handleClickSubmit() {
                this.$refs.farmRecordForm.validate((valid) => {
                    if (valid) {
                        const goodsArray = []
                        const machineryArray = []
                        if(this.putTableData.length>0){
                            this.putTableData.map(item=>{
                                if(item.id){
                                    const obj = {
                                        kcId: item.id,
                                        goodsId: item.goodsId,
                                        price: item.price,
                                        qty: item.inputs
                                    }
                                    goodsArray.push(obj)
                                }
                            })
                        }
                        if(this.putMachineTableData.length>0){
                            this.putMachineTableData.map(item=>{
                                if(item.id){
                                    const obj = {
                                        kcId: item.id,
                                        machineryId: item.machineryId,
                                        price: parseFloat(item.inputCost)*100,
                                        qty: item.time
                                    }
                                    machineryArray.push(obj)
                                }
                            })
                        }
                        // if(goodsArray.length==0 && machineryArray.length==0){
                        //     this.$message({type:"warn", message:"农资或农机不能为空"})
                        //     return
                        // }
                        const formData = this.$cloneDeep(this.farmRecordForm)
                        const params = {
                            ids:this.targetIds.map(item=>item.id),
                            farmType:formData.eventType,
                            dealTime:formData.handleTime,
                            remarks: formData.remarks,
                            stockGoodsOutDetail:JSON.stringify(goodsArray),
                            stockMachineryOutDetail:JSON.stringify(machineryArray)
                        }
                        this.addStatus = true
                        batchAddFarmRecord(params).then(res=>{
                            console.log(res)
                            this.addStatus = false
                            this.dialogFormVisible = false
                            if(res.data.code==200){
                                this.$message({type:"success", message:res.data.msg})
                            }else{
                                this.$message({type:"error", message:res.data.msg})
                            }
                        }).catch(err=>{
                            this.addStatus = false
                            this.dialogFormVisible = false
                            this.$message({type:"error", message:"批量添加农事记录失败:"+err})
                        })
                    }
                })

            },
            changeGoodsInputs(e,index){
                const reg = /^-?(([0-9]*(\.[0-9]{1,3})$)|([0-9]+$))/
                if(!reg.test(e.inputs)){
                    this.$message({type:"warn", message:"只能输入数字"})
                    return
                }

                if(this.putTableData[index].maxInputs<e.inputs*1){
                    this.$message({type:"warn", message:"不能超过该农资的最大量"})
                    e.inputs = 0
                }
            },
            changeCostInputs(e,index){
                const reg = /^-?(([0-9]*(\.[0-9]{1,3})$)|([0-9]+$))/
                if(!reg.test(e.inputCost)){
                    this.$message({type:"warn", message:"只能输入数字"})
                    return
                }
            },
            changeTimeInputs(e,index){
                const reg = /^-?(([0-9]*(\.[0-9]{1,3})$)|([0-9]+$))/
                if(!reg.test(e.time)){
                    this.$message({type:"warn", message:"只能输入数字"})
                    return
                }
            },
            handleChangeGoods(e,index){
                const objIndex = this.materialOptions.findIndex(item=>item.id==e)
                this.materialDeleteOptions.push(this.materialOptions[objIndex])
                const objById = JSON.parse(JSON.stringify(this.materialDeleteOptions[this.materialDeleteOptions.length-1]))
                this.putTableData[index]['material'] = objById.goodsName
                this.putTableData[index]['goodsId'] = objById.goodsId
                this.putTableData[index]['materialType'] = objById.goodsTypeName
                this.putTableData[index]['materialBrand'] = objById.brand
                this.putTableData[index]['model'] = objById.model
                this.putTableData[index]['meteringUnit'] = objById.meteringUnit
                this.putTableData[index]['unit'] = objById.unit
                this.putTableData[index]['specs'] = objById.specs*1
                this.putTableData[index]['maxInputs'] = objById.qty
                this.putTableData[index]['id'] = objById.id
                this.putTableData[index]['inputs'] = 0
                this.putTableData[index]['price'] = objById.price
                this.putTableData[index]['selectStatus'] = true
                this.materialOptions.splice(objIndex,1)
            },
            handleChangeMachine(e,index){
                const objIndex = this.machineTypeOptions.findIndex(item=>item.id==e)
                this.machineTypeDeleteOptions.push(this.machineTypeOptions[objIndex])
                const objById = JSON.parse(JSON.stringify(this.machineTypeDeleteOptions[this.machineTypeDeleteOptions.length-1]))
                this.putMachineTableData[index]['id'] = objById.id
                this.putMachineTableData[index]['machineryName'] = objById.machineryName
                this.putMachineTableData[index]['machineryId'] = objById.machineryId
                this.putMachineTableData[index]['machineryTypeName'] = objById.machineryTypeName
                this.putMachineTableData[index]['brand'] = objById.brand
                this.putMachineTableData[index]['model'] = objById.model
                this.putMachineTableData[index]['inputCost'] = objById.price ? parseFloat(objById.price)/100 : 0
                this.putMachineTableData[index]['time'] = 0
                this.putMachineTableData[index]['price'] = objById.price
                this.putMachineTableData[index]['selectStatus'] = true
                this.machineTypeOptions.splice(objIndex,1)
            },
            handleClickAddItem() {
                const obj = {id:"", material: "", materialType: "", materialBrand: "", model: "", meteringUnit: "", unit:"", specs:"", inputs:"", maxInputs:"", selectStatus:false}
                this.putTableData.push(obj)
            },
            handleClickAddMachine(){
                const obj = {id:"", machineryName: "", machineryTypeName: "", brand: "", model: "", inputCost: "", time:"", maxInputs:"", selectStatus:false}
                this.putMachineTableData.push(obj)
            },
            handleClickDelete(row, index) {
                const obj = this.putTableData[index]
                if(obj && obj.id){
                    const delIndex = this.materialDeleteOptions.findIndex(item=>item.id==obj.id)
                    this.materialOptions.push(this.$cloneDeep(this.materialDeleteOptions[delIndex]))
                    this.materialDeleteOptions.splice(delIndex,1)
                }
                this.putTableData.splice(index, 1)
            },
            handleClickDeleteMachine(row, index){
                const obj = this.putMachineTableData[index]
                if(obj && obj.id){
                    const delIndex = this.machineTypeDeleteOptions.findIndex(item=>item.id==obj.id)
                    this.machineTypeOptions.push(this.$cloneDeep(this.machineTypeDeleteOptions[delIndex]))
                    this.machineTypeDeleteOptions.splice(delIndex,1)
                }
                this.putMachineTableData.splice(index, 1)
            },

            async getAllList(){
                const responses = await Promise.all([goodsKCList(),machineryKCList()])
                if(responses[0].data.code == 200){
                    this.materialOptions = []
                    if(responses[0].data.rows && responses[0].data.rows.length>0){
                        responses[0].data.rows.forEach(item=>{
                            if(item.qty && item.qty*1>0 && item.goodsName){
                                this.materialOptions.push(item)
                            }
                        })
                    }
                }
                if(responses[1].data.code == 200){
                    this.machineTypeOptions = []
                    if(responses[1].data.rows && responses[1].data.rows.length>0){
                        responses[1].data.rows.forEach(item=>{
                            if(item.qty && item.qty*1>0 && item.machineryName){
                                this.machineTypeOptions.push(item)
                            }
                        })
                        // console.log("this.materialOptions",responses[1].data.rows)
                    }
                }
            },
            open() {
                this.farmEventOptions = []
                this.machineTypeOptions = []
                this.machineTypeDeleteOptions = []
                this.modelOptions = []
                this.materialOptions = []
                this.materialDeleteOptions = []
                this.categoryOptions = []
                try {
                    this.$refs.farmRecordForm.resetFields()
                    this.$refs.farmRecordForm.clearValidate()
                } catch (e) {
                }
                this.getAllList()
                queryPlantType().then(res=>{
                    if(res.data.code==200){
                        if(res.data.data && res.data.data.length){
                            this.farmEventOptions = res.data.data.map(item=>{
                                return {
                                    eventId: item.dictValue,
                                    eventName: item.dictLabel
                                }
                            })
                        }
                    }
                    console.log("1",this.farmEventOptions)
                }).catch(err=>{
                    this.$message({type: "error", message: err})
                })
            },
            close() {
                this.putTableData = []
                this.putMachineTableData = []
                try {
                    Object.assign(this.$data.farmRecordForm, this.$options.data().farmRecordForm)
                } catch (e) {
                }
                this.$refs.farmRecordForm.resetFields()
                this.$refs.farmRecordForm.clearValidate()
            },
            // 已弃用
            handleChangeMachine1(item) {
                typelistMaterial({goodType: "farm_machine"}).then(res => {
                    if (res.data.code == 200) {
                        console.log("res.data.data", res.data.data)
                        this.modelOptions = res.data.data
                    }
                })

                typelistMaterial({goodType: "farm_machine", level: 3, parentId: item * 1}).then(res => {
                    this.modelOptions = []
                    if (res.data.code == 200) {
                        if (res.data.data && res.data.data.length > 0) {
                            this.modelOptions = res.data.data.map(item => {
                                return {
                                    machineId: item.id,
                                    machineName: item.goodName,
                                    children: item.children
                                }
                            })
                        }
                    }
                    console.log(this.modelOptions)
                }).catch(err => {
                    this.$message({type: "error", message: err})
                })

            },
            // 设置表头样式
            tableHeaderColor({row, column, rowIndex, columnIndex}) {
                return 'background-color:#F2F2F2;color:#000;font-weight: 500;height:38px;'
            },
            // 设置斑马样式
            tableRowClassName({row, rowIndex}) {
                if (rowIndex % 2 === 0) {
                    return 'columns-row-b';
                } else if (rowIndex % 2 === 1) {
                    return 'columns-row-a';
                }
            }
        }
    }
</script>
<style>
  .el-table .columns-row-a {
    background: #f1faf7;
  }

  .el-table .columns-row-b {
    background: #ffffff;
  }
</style>
<style scoped>
  .custom-dialog >>> .el-dialog {
    width: 900px !important;
    position: relative;
  }

  .custom-dialog >>> .el-dialog__header {
    background: #009865;
    padding: 10px 10px 10px;
  }

  .custom-dialog >>> .el-dialog__headerbtn {
    top: 9px !important;
    right: 10px !important;
  }

  .custom-dialog >>> .el-dialog__body {
    line-height: 0px !important;
  }

  .custom-dialog >>> .el-input.is-disabled .el-input__inner {
    background-color: #fff;
    color: #606266;
  }

  .custom-dialog >>> .el-textarea.is-disabled .el-textarea__inner {
    background-color: #fff;
    color: #606266;
  }
</style>
